package mo.offer_special;

import mo.common.TreeNode;

import java.util.*;

public class L046 {

    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        Map<Integer, Integer> depth2val = new HashMap<>();
        int maxDepth = -1;
        Stack<TreeNode> queue = new Stack<>();
        Stack<Integer> depthQueue = new Stack<>();
        queue.add(root);
        depthQueue.add(0);

        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            Integer depth = depthQueue.pop();
            maxDepth = Math.max(depth, maxDepth);

            if (!depth2val.containsKey(depth)) {
                depth2val.put(depth, node.val);

            }
            if (node.left != null) {
                queue.push(node.left);
                depthQueue.push(depth+1);
            }
            if (node.right != null) {
                queue.push(node.right);
                depthQueue.push(depth+1);
            }
        }
        List<Integer> res = new ArrayList<>(maxDepth+1);
        for (int i = 0; i <= maxDepth; i++) {
            res.add(depth2val.get(i));
        }
        return res;
    }

}
